package com.ittest.web.filters;

import com.ittest.domain.system.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 不登录不能访问其他页面过滤器
 * @author
 * @Company
 */
@WebFilter(value = "/*")
public class LoginFilter implements Filter {

    private FilterConfig filterConfig;

    /**
     * 初始化方法，获取过滤器的配置对象
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        //1.定义和协议相关的请求和响应对象
        HttpServletRequest request ;
        HttpServletResponse response;
        try{
            //2.把参数转换成协议相关的对象
            request = (HttpServletRequest)req;
            response = (HttpServletResponse)resp;

            //获取路径放行index.jsp和login.jsp
            String uri = request.getRequestURI();
            if (uri.endsWith("login.jsp")
                    || uri.endsWith("index.jsp")
                    || uri.endsWith(".css")
                    || uri.endsWith(".js")
                    || uri.endsWith(".png")
                    || uri.endsWith(".jpg")
                    || uri.endsWith("/")
                    || uri.endsWith("/pages/common/failer.jsp")
                    || uri.endsWith("/system/user/login")
                    || uri.contains("/system/sysLog")
                    || uri.endsWith("/system/user/autoLogin")
            ){
                //放行登录和index页面
                chain.doFilter(request,response);
                return;
            }
            //获取session
            HttpSession session = request.getSession();
            // 从session里取的用户名信息
            //这里获取session，为了检查session里有没有保存用户信息，没有的话转发到登陆页面
            User loginUser = (User) session.getAttribute("loginUser");
            // 判断如果没有取到用户信息,就跳转到登陆页面
            if (loginUser == null )
            {
                // 跳转到登陆页面
                req.getRequestDispatcher(request.getContextPath()+"/login.jsp").forward(request,response);
            }
            else
            {
                // 已经登陆,继续此次请求
                chain.doFilter(request,response);
            }


        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void destroy() {
        //可以做一些清理操作
    }
}
